package pers.whj.security;

import java.nio.charset.StandardCharsets;
import java.util.Base64;

public class XOR {
    /**
     * encrypt the plain text
     *
     * @param plainText specified text
     * @param password  specified password
     * @return the cipher text
     */
    public static String encrypt(String plainText, String password) {
        byte[] arr = plainText.getBytes(StandardCharsets.UTF_8);
        return new String(encrypt(arr, 0, arr.length, password), StandardCharsets.UTF_8);
    }

    /**
     * encrypt the plain text
     *
     * @param plainText specified text
     * @param offset    from index
     * @param length    length to encrypt
     * @param password  specified password
     * @return the cipher text in byte array
     */
    public static byte[] encrypt(byte[] plainText, int offset, int length, String password) {
        byte[] input = new byte[length];
        System.arraycopy(plainText, offset, input, 0, length);
        byte[] key = password.getBytes(StandardCharsets.UTF_8);
        int keyLen = key.length;
        int i = 0, j = 0;
        for (; i < input.length; i++) {
            input[i] ^= key[j];
            j++;
            if (j == keyLen) {
                j = 0;
            }
        }
        return Base64.getEncoder().encode(input);
    }

    /**
     * decrypt the cipher text
     *
     * @param cipherText specified text
     * @param password   specified password
     * @return the plain text
     */
    public static String decrypt(String cipherText, String password) {
        byte[] arr = cipherText.getBytes(StandardCharsets.UTF_8);
        return new String(decrypt(arr, 0, arr.length, password), StandardCharsets.UTF_8);
    }

    /**
     * decrypt the cipher text
     *
     * @param cipherText specified text
     * @param offset     from index
     * @param length     length to decrypt
     * @param password   specified password
     * @return the plain text in byte array
     */
    public static byte[] decrypt(byte[] cipherText, int offset, int length, String password) {
        byte[] input = new byte[length];
        System.arraycopy(cipherText, offset, input, 0, length);
        input = Base64.getDecoder().decode(input);
        byte[] key = password.getBytes(StandardCharsets.UTF_8);
        int keyLen = key.length;
        int i = 0, j = 0;
        for (; i < input.length; i++) {
            input[i] ^= key[j];
            j++;
            if (j == keyLen) {
                j = 0;
            }
        }
        return input;
    }
}